package com.yrxy.thread.interview.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;
/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className StampedLockDemo
 * @description：
 * @date 2017/6/29 14:30
 */
public class StampedLockDemo {
    int value = 0;
    public static void main(String[] args) {
        StampedLock stampedLock = new StampedLock();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        StampedLockDemo cst = new StampedLockDemo();
        // Runnable as lambda - read
        Runnable readTask = ()->{
            long stamp = stampedLock.readLock();
            try{
                System.out.println("read value " + cst.getValue());
            }finally{
                stampedLock.unlockRead(stamp);
            }
        };
        // Runnable as lambda - Write lock
        Runnable writeTask = ()->{
            long stamp = stampedLock.writeLock();
            try {
                cst.increment();
            }finally{
                stampedLock.unlockWrite(stamp);
            }
        };
        // 3 write tasks
        executor.submit(writeTask);
        executor.submit(writeTask);
        executor.submit(writeTask);
        // 1 read task
        executor.submit(readTask);
        executor.shutdown();

    }
    public  void increment() {
        value++;
        System.out.println("write ， in increment " + value);
    }

    public  int getValue() {
        return value;
    }

}
